package com.lhz.services;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lhz.dao.StaffDao;
import com.lhz.dao.StaffDao2;
import com.lhz.dao.mybatis.StaffShowMybatis;
import com.lhz.pojos.Staff;
import com.lhz.utils.GetUUID;
/**
 *                 _ooOoo_
 *                o8888888o
 *                88" . "88
 *                (| -_- |)
 *                O\  =  /O
 *             ____/`---'\____
 *           .'  \\|     |//  `.
 *          /  \\|||  :  |||//  \
 *         /  _||||| -:- |||||-  \
 *         |   | \\\  -  /// |   |
 *         | \_|  ''\---/''  |   |
 *         \  .-\__  `-`  ___/-. /
 *       ___`. .'  /--.--\  `. . __
 *    ."" '<  `.___\_<|>_/___.'  >'"".
 *   | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *   \  \ `-.   \_ __\ /__ _/   .-` /  /
 *====`-.____`-.___\_____/___.-`____.-'======
 *                 `=---='
 *^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *             佛祖保佑       永无BUG
 */
@Service
@Transactional
public class StaffService {
	
	
	@Autowired
	private StaffDao staffDao;
	@Autowired
	private StaffDao2 staffDao2;
	@Autowired  
	private HttpSession session; 
	
	@Autowired
	private StaffShowMybatis mybatisdao;
	@Autowired
	HttpServletRequest request;
	
	/**
	 * 员工登录
	 * @param staffId
	 * @param password
	 * @return
	 */
	public String login(String staffId,String password) {
		Staff staff=staffDao.findByStaffIdAndPassword(staffId, password);
		if(staff==null) {
			return "用户名或密码错误";
		}
		session.setMaxInactiveInterval(60 * 60); 
        //把用户数据保存在session域对象中
        session.setAttribute("info", staff);
        Staff staff2=(Staff) session.getAttribute("info");
        System.out.println(staff2);
		return "登录成功";
	}
	
	/**
	 * 修改密码
	 * @param staffId
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	public String updatePassword(String staffId,String oldPassword,String newPassword) {
		Staff staff=staffDao.findByStaffIdAndPassword(staffId, oldPassword);
		if(staff==null) {
			return "原密码不正确";
		}
		staff.setPassword(newPassword);
		return "修改成功";
	}
	
	/**
	 * 修改员工信息
	 * @param staff
	 * @return
	 */
	public String updateStaffInfo(Staff staff) {
		Staff findByStaffId = staffDao.findByStaffId(staff.getStaffId());
		if(findByStaffId==null) {
			return "找不到该员工";
		}
		findByStaffId.setAddress(staff.getAddress());
		findByStaffId.setAge(staff.getAge());
		findByStaffId.setBirthday(staff.getBirthday());
		findByStaffId.setImage(staff.getImage());
		return "修改成功";
	}
	
	/**
	 * 显示员工 还要增加一条分页查询记录出来
	 * @return
	 */
	public Map<String, Object> staffshows(int pageNum,int pageSize){
			Staff sta=new Staff();
			// 查询数据
			PageHelper.startPage(pageNum, pageSize);
 			List<Staff> pageData = mybatisdao.searchByStaInfo(sta);
 			PageInfo<Staff> info = new PageInfo<>(pageData);
			Map<String, Object> map=new HashMap<>();
			if(info!=null) {
				// 组装返回结果
				map.put("total", info.getTotal());
				map.put("rows", info.getList());
				map.put("staffll", pageData);
			}
				
			return map;
	}		
	/**
	 * 按条件查询员工信息
	 * @param staffId
	 * @param name
	 * @param sex
	 * @return
	 */
	public Map<String,Object> searchByshow(String staffId,String name,String sex){
		Map<String,Object> map=new HashMap<>();
		List<Staff> info = mybatisdao.searchByStaInfo(staffId, name, sex);
		if(info!=null) {
			map.put("staffll", info);
		}else {
			throw new RuntimeException("没有查到员工相关信息出来....");
		}
		return map;
  
		
	}
	
	/**
	 * 添加一个员工信息
	 * @param sta
	 * @return
	 */
	public Map<String, Object> stfaddall(Staff sta){
		Map<String, Object> map=new HashMap<>();
		Staff s=new Staff();
		String id = mybatisdao.maxStaffId(); //sta8 +1 =sta9
		String firstThree=id.substring(0,3); //获取最大id前三位 sta
		String num=id.substring(3, id.length());
		int newNum=Integer.parseInt(num)+1;
		s.setStaffId(firstThree+String.format("%03d", newNum));
		s.setName(sta.getName());
		s.setSex(sta.getSex());
		s.setAge(sta.getAge());
		s.setZhiwei(sta.getZhiwei());
		s.setBirthday(sta.getBirthday());
		s.setAddress(sta.getAddress());
		s.setPersonId(sta.getPersonId());
		Staff save = staffDao.save(s);
		if(save!=null) {
			map.put("staffll", staffDao.findAll());
		}else {
			 map.put("message", "添加失败！");
			 throw new RuntimeException("添加员工有误!....."); 
		}
		return map;
		
	}
	
	/**
	 * 根据状态查询
	 * @param status
	 * @return
	 */
	public Map<String, Object> searchByStatus(Long status){
		Map<String,Object> map=new HashMap<>();
		List<Staff> status2 = mybatisdao.searchByStatus(status);
		if(status2!=null) {
			map.put("staffll", status2);
		}else {
			throw new RuntimeException("状态查询员工信息有误!...");
		}
		return map;
	}
	
	/**
	 * 图片上传
	 * @param staffId
	 * @param staffimg
	 * @param file
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@SuppressWarnings("null")
	public Map<String,Object> uploadStaffImg(String staffId,MultipartFile file) throws IllegalStateException, IOException{
 		Map<String,Object> map=new HashMap<>();
  		if(file==null||file.isEmpty()||file.getSize()<=0) {
  			map.put("message", "没有图片!");
 			return map;
 		}
 		//判断上传文件格式和上传的大小
 		String oldFileName=file.getOriginalFilename();//获取文件名
  		String[] a = oldFileName.split("\\.");
 		System.err.println("SSSSSSSSSSSSSSSS:"+a[1]);
 		if (!(a[1].equals("jpg") || a[1].equals("bmp") || 
 				a[1].equals("gif") ||a[1].equals("png")||
 				a[1].equals("jpeg"))) {
 			 map.put("message","图片格式有误!");
 			 return map;
 		 }
		// 获取目录
		String uploads =  request.getSession().getServletContext().getRealPath("/upload");//获取服务器指定文件存取路径  
		System.out.println(uploads);
		File dir = new File(uploads + "\\upload");
		if (!dir.exists()) {
			dir.mkdirs();//创建路径
		}
		String newFileName = GetUUID.getNewFileName(oldFileName);//给文件生成一个唯一文件名追加上后缀
		String fullFileName = uploads + "\\" + newFileName;
		File writeFile=new File(fullFileName);
		writeFile.createNewFile();
        file.transferTo(writeFile);  //转存文件  
        
        //查出数据库中的文件进行删除
        Staff sta = staffDao.findByStaffId(staffId);
         if(sta.getImage()!=null) {
        	sta.setImage(null);
        }
        
         	sta.setImage(newFileName);
        Staff save = staffDao.save(sta);
        if(save!=null) {
        	map.put("result", "上传成功!");
        }else {
        	map.put("message", "上传失败!");
        }
   /*     
		List<Staff> info = mybatisdao.searchByStaInfo(sta);
		 map.put("staffll", info);*/
		 return map;
		 
		
	}
	
	
/**
 * 删除员工	
 * @param staffId
 * @return
 */
	public Map<String,Object> delectStaffStatus(String staffId){
 		Map<String,Object> map=new HashMap<>();
 		String uploads = request.getSession().getServletContext().getRealPath("/upload");
		Staff findByStaffId = staffDao.findByStaffId(staffId);
		if(findByStaffId!=null) {
			//删除员工之后删掉服务器上图片
			File file=new File(uploads+"\\"+findByStaffId.getImage());
			if(file.exists()) {
				file.delete();
			}
			staffDao.delete(findByStaffId);
 			map.put("result", "删除成功!");
		}else {
			 map.put("message", "删除失败!");
		}
		return map;
		 
	}
	/**
	 * 是否解雇或者复职
	 * @param staffId
	 * @param status
	 * @return
	 */
	public Map<String,Object> updateState(String staffId,String status){
		int a=0;
		if(status.equals("解雇")) {
			a=1;
		}
		if(status.equals("复职")) {
			a=0;
		}
		Map<String,Object> map=new HashMap<>();
		Staff findByStaffId = staffDao.findByStaffId(staffId);
		findByStaffId.setStatus(a);
		Staff save = staffDao.save(findByStaffId);
		if(save!=null) {
			map.put("result", "操作成功!");
		}else {
			map.put("message", "操作失败!");
		}
		return map;
	}
	
	/**
	 * 通过Id查找到员工信息
	 * @param staffId
	 * @return
	 */
	public Map<String, Object> staffAlter(String staffId){
		Map<String, Object> map=new HashMap<>();
		if(staffId!=null) {
		}else {
			throw new RuntimeException("没有这个staffId");
		}
		  List<Staff> findOne = staffDao2.findByStaffId(staffId);
		if(findOne!=null) {
			map.put("sta",findOne);
		}else {
			map.put("message","查找失败!");
			throw new RuntimeException("没有找到..");
		}
	
		return  map;
	}
	/**
	 * 根据Id来修改员工信息
	 * @param staffId
	 * @param sta
	 * @return
	 */
	public Map<String,Object> updateEmployee(Staff sta){
	 
			Map<String, Object> map=new HashMap<>();
	 		Staff s=new Staff();
	 		//修改员工还要进行校验 修改的信息是不是合法与数据库中数据是否相同
			s.setStaffId(sta.getStaffId());
			s.setName(sta.getName());
			s.setSex(sta.getSex());
			s.setAge(sta.getAge());
			s.setZhiwei(sta.getZhiwei());
			s.setBirthday(sta.getBirthday());
			s.setAddress(sta.getAddress());
			s.setPersonId(sta.getPersonId());
			Staff save = staffDao.save(s);
			if(save!=null) {
 				map.put("result", "修改成功!");
			}else {
				map.put("message", "修改失败!");
			}
			return map;
 
	}
	
	
	
	
}
